import {StyleSheet, Text, TouchableOpacity, View, ImageBackground, Image, ScrollView, Dimensions} from 'react-native'
import React, {useEffect, useState, useRef} from 'react'
import PageScrollView from "@/components/PageScrollView";
import useGetStorage from "@/hooks/useGetStorage";
import Animated, {useAnimatedRef, useAnimatedScrollHandler, useSharedValue} from "react-native-reanimated";
import {Flex} from "@ant-design/react-native";

import {
  useGetPosterListMutation,
  useGetAccountInfoMutation,
  useGetToolListMutation,
  useGetVideoCaseListMutation
} from "@/store/api/home/homeApi";


type Props = {}

const index = (props: Props) => {
  const [bannerList, setBannerList] = useState([])
  const [bannerIndex, setBannerIndex] = useState<any>(0)
  const [accountInfo, setAccountInfo] = useState<any>({})
  const [toolList, setToolList] = useState<any>([])
  const [toolTabList, setToolTabList] = useState<any>([
    {
      label:'推荐工具',
      value: null
    },
    {
      label:'内容创作工具',
      value:1
    },
    {
      label:'私有资料投喂',
      value:2
    },
    {
      label:'AI一键成片工具',
      value:3
    },
    {
      label:'账号运营工具',
      value:4
    },
    {
      label:'客服管理工具',
      value:5
    },
    {
      label:'客户管理工具',
      value:6
    }
  ])
  const [toolIndex, setToolIndex] = useState<any>(null)
  const [caseList, setCaseList] = useState<any>([])
  const [userInfo, setUserInfo] = useState<any>({})
  
  const timer:any = useRef(null)
  const activeBanner = useSharedValue(0);
  const flatListRef = useAnimatedRef<Animated.FlatList<any>>();
  const screenWidth = Dimensions.get('window').width;

  const [getPosterListFun] = useGetPosterListMutation()
  const [getAccountInfoFun] = useGetAccountInfoMutation()
  const [getToolListFun] = useGetToolListMutation()
  const [getVideoCaseListFun] = useGetVideoCaseListMutation()

  useEffect(() => {
    getPosterList()
    getAccountInfo()
    getToolList()
    getVideoCaseList()

    useGetStorage('userInfo').then(res => {
      if(res?.userInfo) setUserInfo(res.userInfo)
    })
  }, []);

  //获取轮播图
  const getPosterList = () => {
    getPosterListFun({}).then(res => {
      let arr = res.data?.result?.records || []
      setBannerList(arr)

      clearInterval(timer.current)

      let scrollValue = 0

      timer.current = setInterval(() => {
        if(activeBanner.value == arr.length - 1){
          scrollValue = 0
          setBannerIndex(0)
        }else{
          scrollValue += (screenWidth - 32)
          setBannerIndex(bannerIndex + 1)
        }

        flatListRef.current.scrollToOffset({
          offset: scrollValue,
          animated: true,
        });
      }, 4000);
    })
  }

  //获取统计信息
  const getAccountInfo = () => {
    getAccountInfoFun({}).then(res => {
      setAccountInfo(res.data.result)
    })
  }

  //获取推荐工具
  const getToolList = () => {
    getToolListFun({}).then(res => {
      setToolList(res.data.result?.records)
    })
  }

  //获取精选案例
  const getVideoCaseList = () => {
    getVideoCaseListFun({}).then(res => {
      setCaseList(res.data.result?.records)
    })
  }

  const onScrollHandler = useAnimatedScrollHandler({
    onScroll: (e) => {
      activeBanner.value = Math.ceil(e.contentOffset.x / (screenWidth - 32))
    }
  })

  return (
    <ImageBackground 
      source={require('@/assets/images/public/home_bg.png')}
      style={{flex: 1, width: '100%'}}
    >
      <PageScrollView
        themedStyle={{backgroundColor: 'transparent'}}
      >
        <View>
          <Flex justify='between'>
            <Flex style={styles.deliver_name}>
              <Image style={styles.deliver_img} source={require('@/assets/images/index/tx.png')} resizeMode={'contain'}></Image>
              <Text style={{marginLeft: 40, fontSize: 12}}>专属交付顾问：常洋辉</Text>
            </Flex>

            <View>
              <TouchableOpacity activeOpacity={0.8} >
                <Image style={{width: 25, height: 25}} source={require('@/assets/images/index/syh_icon.png')} resizeMode={'contain'}></Image>
              </TouchableOpacity>
            </View>
          </Flex>

          <Animated.FlatList
            ref={flatListRef}
            style={{width: screenWidth - 32, borderRadius: 8, marginVertical: 12}}
            data={bannerList}
            keyExtractor={(_, index) => `list_item${index}`}
            renderItem={({item,index}: { item: any; index: number }) => (
              <ImageBackground
                source={{uri: item.imgUrl}}
                style={{ width: screenWidth - 32, height: 100}}
              >
                <Flex justify='between' style={{flex: 1, paddingHorizontal: 30, position: 'relative'}}>
                  <View>
                    <Text style={{color: '#FFF', fontSize: 18, fontWeight: 'bold'}}>{item.name}</Text>
                    <Text style={{color: '#FFF', fontSize: 12, fontWeight: 'bold', marginTop: 5}}>{item.subTitle}</Text>
                  </View>

                  <Image style={{width: 120, height: '100%'}} source={{uri: item.mainUrl}} resizeMode={'contain'}></Image>

                  <Flex style={styles.banner_transition}>
                    {
                      bannerList?.map((val:any, idx:any) => (
                        <View key={idx} style={[styles.banner_box, bannerIndex == idx ? styles.banner_active : null]}></View>
                      ))
                    }
                  </Flex>
                </Flex>
              </ImageBackground>
            )}
            horizontal
            showsHorizontalScrollIndicator={false}
            pagingEnabled
            onScroll={onScrollHandler}
            scrollEventThrottle={16}
          />

          <View style={styles.statistics}>
            <Flex justify='between'>
              <Flex>
                <Image style={{width: 24, height: 24, borderRadius: 24}} resizeMode={'contain'} source={{uri: userInfo?.avatar}}></Image>
                <Text style={{color: '#3D3D3D', marginLeft: 5}}>{userInfo?.realname}</Text>
              </Flex>
              <Text style={{color: 'rgba(0, 0, 0, 0.3)', fontSize: 12}}>数据实时更新</Text>
            </Flex>
            <View style={{borderTopWidth: 0.5, borderTopColor: '#D8D8D8', marginVertical: 12}}></View>

            <View>
              <Flex justify='between'>
                <View style={{width: '33%'}}>
                <Text style={styles.statistics_count}>{accountInfo.aiCaseNum}</Text>
                  <Text style={styles.statistics_text}>文案生成数</Text>
              </View>
                <View style={{width: '33%'}}>
                <Text style={styles.statistics_count}>{accountInfo.contentNum}</Text>
                  <Text style={styles.statistics_text}>导入内容管理数</Text>
              </View>
                <View style={{width: '33%'}}>
                <Text style={styles.statistics_count}>{accountInfo.projectNum}</Text>
                  <Text style={styles.statistics_text}>AI成片数</Text>
              </View>
              </Flex>

              <Flex justify='between' style={{marginTop: 12}}>
                <View style={{width: '33%'}}>
                  <Text style={styles.statistics_count}>{accountInfo.text2ImgNum}</Text>
                  <Text style={styles.statistics_text}>文生图片数</Text>
                </View>
                <View style={{width: '33%'}}>
                  <Text style={styles.statistics_count}>{accountInfo.video2ImgNum}</Text>
                  <Text style={styles.statistics_text}>文生视频数</Text>
                </View>
                <View style={{width: '33%'}}>
                  <Text style={styles.statistics_count}>{accountInfo.localVideoNum}</Text>
                  <Text style={styles.statistics_text}>本地成片数</Text>
              </View>
            </Flex>
          </View>
          </View>

          <ScrollView
            horizontal
            showsHorizontalScrollIndicator={false}
            contentContainerStyle={{paddingVertical: 12}}
          >
            <Flex>
              <Image style={{width: 24, height: 24, marginRight: 5}} resizeMode={'contain'} source={require('@/assets/images/AIWrite.png')}></Image>
              {
                toolTabList.map((item:any, index:any) => (
                  <TouchableOpacity key={index} onPress={() => setToolIndex(item.value)}>
                    <Text style={[styles.toolTab_item, toolIndex == item.value ? styles.toolActive : null]}>{item.label}</Text>
                  </TouchableOpacity>
                ))
              }
            </Flex>
          </ScrollView>

          <ScrollView
            horizontal
            showsHorizontalScrollIndicator={false}
          >
            {
              toolList.filter((val:any) => toolIndex ? val.type == toolIndex : val).map((item:any, index:any) => (
                <View key={index} style={{marginRight: 8}}>
                  <Image style={{width: 98, height: 175, borderRadius: 8}} resizeMode={'contain'} source={{uri: item.imgUrl}}></Image>
                  <Text style={{textAlign: 'center', marginTop: 5, fontSize: 12}}>{item.name}</Text>
                </View>
              ))
            }
          </ScrollView>

          <View style={{marginTop: 16}}>
            <Flex>
              <Image style={{width: 18, height: 18, marginRight: 8}} resizeMode={'contain'} source={require('@/assets/images/hot.png')}></Image>
              <Text style={styles.toolActive}>精选案例</Text>
            </Flex>

            <Flex wrap='wrap' justify='between' style={{marginTop: 8}}>
              {
                caseList.map((item:any, index:any) => (
                  <View key={index} style={{width: '49%', marginBottom: 15}}>
                    <View>
                      <Image style={{width: '100%', height: 300, borderRadius: 8}} resizeMode={'cover'} source={{uri: item.avatar}}></Image>
                      <Flex justify='between' style={{position: 'absolute', bottom: 10, width: '100%', paddingHorizontal: 20}}>
                        <Flex direction='column' justify='center'>
                          <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'rgba(255, 255, 255, 0.6)'}}>&#xe610;</Text>
                          <Text style={{fontSize: 10, marginTop: 5, color: 'rgba(255, 255, 255, 0.6)'}}>{item.commentNum > 10000 ? item.commentNum/10000 + 'w' : item.commentNum}</Text>
                        </Flex>

                        <Flex direction='column' justify='center'>
                          <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'rgba(255, 255, 255, 0.6)'}}>&#xe622;</Text>
                          <Text style={{fontSize: 10, marginTop: 5, color: 'rgba(255, 255, 255, 0.6)'}}>{item.diggNum > 10000 ? item.diggNum/10000 + 'w' : item.diggNum}</Text>
                        </Flex>

                        <Flex direction='column' justify='center'>
                          <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'rgba(255, 255, 255, 0.6)'}}>&#xe7de;</Text>
                          <Text style={{fontSize: 10, marginTop: 5, color: 'rgba(255, 255, 255, 0.6)'}}>{item.forwardNum > 10000 ? item.forwardNum/10000 + 'w' : item.forwardNum}</Text>
                        </Flex>
                      </Flex>
                    </View>
                    <Text style={{marginTop: 5, fontSize: 12, lineHeight: 20}} numberOfLines={2}>{item.title}</Text>
                  </View>
                ))
              }
            </Flex>
          </View>
        </View>
        
      </PageScrollView>
    </ImageBackground>
  )
}

export default index

const styles = StyleSheet.create({
  deliver_name: {
    width: 180,
    height: 32,
    color: '#3D3D3D',
    borderRadius: 48,
    position: 'relative',
    backgroundColor: '#FFF',
    marginTop: 10
  },
  deliver_img: {
    position: 'absolute',
    left: 0,
    width: 32,
    height: 32,
  },
  banner_transition: {
    position: 'absolute',
    bottom: 10,
    right: '50%',
    transform: [{ translateX: '-50%' }]
  },
  banner_box: {
    width: 4,
    height: 4,
    marginRight: 5,
    borderRadius: 4,
    backgroundColor: '#FFF',
  },
  banner_active: {
    width: 10,
    borderRadius: 5,
  },
  statistics: {
    padding: 12,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: '#e2e2e3',
    backgroundColor: 'rgba(255, 255, 255, 0.5)',
  },
  statistics_count: {
    fontWeight: '500',
    textAlign: 'center',
    marginBottom: 5,
    lineHeight: 16,
  },
  statistics_text: {
    textAlign: 'center',
    fontSize: 12,
    color: 'rgba(0, 0, 0, 0.5)'
  },
  toolTab_item: {
    marginRight: 25,
    color: 'rgba(0, 0, 0, 0.5)',
    fontWeight: '400',
  },
  toolActive: {
    fontFamily: 'DingTalk JinBuTi',
    color: 'rgba(0, 0, 0, 0.9)',
    fontSize: 15,
    fontWeight: '500',
  },
})

